package com.factory.test.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.SeekBar;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.factory.test.R;
import com.factory.test.base.BaseActivity;
import com.factory.test.databinding.ActivityAgingBinding;
import com.factory.test.util.WifiAdmin;
import com.hqw.temp.QDTempModule;
import com.hqw.temp.TempModule;
import com.hqw.temp.TempModuleCallback;
import com.yecontech.sdk.base.camera.CameraManager;
import com.yecontech.sdk.base.gpio.GpioLampLight;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 老化测试
 */
public class AgingTestActivity extends BaseActivity {

    private ActivityAgingBinding binding;
    private CameraManager rgbCameraManager;
    private CameraManager irCameraManager;

    private AudioManager mAudioManager;
    private float mMaxVolume;
    private int mNowVolume;
    protected int soundProgress;
    private TempModule tempModule;
    private GpioLampLight gpioLampLight;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_aging);

//        gpioLampLight = sdkService.getGpioLampLightManager();

//        rgbCameraManager = new CameraManager(context, null);
//        rgbCameraManager.setManualCameraId(CameraManager.CAMERA_ID_RGB);      //相机ID
//        rgbCameraManager.setPreviewSize(1920, 1080);            //设置相机的预览宽高(默认 1280 * 720)
//        binding.rgbView.setSurfaceTextureListener(rgbCameraManager);         //必须在onCreate中绑定SurfaceTexture
//        getLifecycle().addObserver(rgbCameraManager);                       //自动管理相机的生命周期



//        irCameraManager = new CameraManager(context, null);
//        irCameraManager.setManualCameraId(CameraManager.CAMERA_ID_IR);
//        irCameraManager.setPreviewSize(1920, 1080);
//        binding.irView.setSurfaceTextureListener(irCameraManager);
//        getLifecycle().addObserver(irCameraManager);


        binding.seekBar.setProgress(sdkService.getBrightness());
        binding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(progress <= 0){
                    progress = 1;
                }

                sdkService.setBrightness(progress);
                //binding.message.setText(String.format("屏幕亮度: %d%%", progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });



        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mNowVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        soundProgress = (int) (mNowVolume / mMaxVolume * 100);
        binding.value.setText(soundProgress + "%");

        binding.add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                soundProgress += 5;
                if(soundProgress >= 100){
                    soundProgress = 100;
                }
                setSound(soundProgress);
            }
        });

        binding.sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                soundProgress -= 5;
                if(soundProgress <= 0){
                    soundProgress = 0;
                }
                setSound(soundProgress);
            }
        });


        /**
         * GLH模组是全屏测温, 不支持指定区域测温
         */
        //  tempModule = new QDTempModule();   //测温模组实现类必须在主线程实例
        //  tempModule.init(context, null);


        binding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                Log.i("video", "视频加载完成, 开始播放...");
                mp.setLooping(true);

                if(timerTask != null){
                    timerTask.cancel();
                }
                timerTask = new MyTimerTask();
                if(!binding.videoView.isPlaying()){
                    binding.videoView.start();
                }
                new Timer().schedule(timerTask, 0, 1000);
            }
        });

        binding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.start();
                mp.setLooping(true);
                Log.i("video", "播放完成");
            }
        });



        binding.videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.test));
        binding.videoView.start();

        wifiAdmin = new WifiAdmin(context);
        init4G();
        step1();
    }

    private WifiAdmin wifiAdmin;
    private void init4G(){
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        mTelephonyMgr.listen(new PhoneStateListener(){
            @Override
            public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                super.onSignalStrengthsChanged(signalStrength);
                //这个dbm 是2G和3G信号的值, 正常手机信号变化范围是从 -110dBm (差)到 -50dBm (好)之间
                int asu = signalStrength.getGsmSignalStrength();
                int dbm = -113 + 2 * asu;


                String desc = "";
                if (dbm > -75) {
                    desc = "网络很好";
                    binding.network4G.setTextColor(context.getColor(R.color.activity_btn_color_green));
                } else if (dbm > -85) {
                    desc = "网络不错";
                    binding.network4G.setTextColor(context.getColor(R.color.green));
                } else if (dbm > -95) {
                    desc = "网络还行";
                    binding.network4G.setTextColor(Color.YELLOW);
                } else if (dbm > -100) {
                    desc = "网络很差";
                    binding.network4G.setTextColor(Color.RED);
                } else {
                    desc = "网络错误";
                    binding.network4G.setTextColor(Color.RED);
                }
                binding.network4G.setText(desc);
                binding.network4G.append(", 信号强度: " + dbm + "dBm");
            }
        }, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }


    private int agingCount = 0;

    /**
     * 1. 初始化界面
     */
    private void step1(){
        agingCount = 0;
        binding.count.setText("当前老化次数: " + agingCount + ", 扫描失败:" + wifiError);

        int delayMillis = 0;
        if(wifiAdmin.isOpen()){
            binding.networkWifi.setText("正在关闭WIFI...");
            wifiAdmin.closeWifi();
            delayMillis = 5000;
        }
        handler.postDelayed(openWifi, delayMillis);
    }


    private void repeat(){
        agingCount ++;

        binding.count.setText("当前老化次数: " + agingCount + ", 扫描失败:" + wifiError);
        int delayMillis = 0;
        if(wifiAdmin.isOpen()){
            binding.networkWifi.setText("正在关闭WIFI...");
            wifiAdmin.closeWifi();
            delayMillis = 5000;
        }
        handler.postDelayed(openWifi, delayMillis);
    }

    private Runnable openWifi = new Runnable() {
        @Override
        public void run() {
            binding.networkWifi.setText("正在开启WIFI...");
            wifiAdmin.openWifi();
            handler.postDelayed(scanWifi, 5000);
        }
    };

    private Runnable scanWifi = new Runnable() {
        @Override
        public void run() {
            wifiAdmin.startScan();
            binding.networkWifi.setText("正在扫描WIFI...");
            handler.postDelayed(loadWifi, 5000);
        }
    };

    int wifiError = 0;
    private Runnable loadWifi = new Runnable() {
        @Override
        public void run() {
            wifiAdmin.getWifiList();
            List<ScanResult> list = wifiAdmin.getWifiList();
            if(list != null && list.size() > 0){
                String s = WIFIActivity.scanResultToString(list);
                binding.networkWifi.setText(Html.fromHtml(s));
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        repeat();
                    }
                }, 10000);
            }

            if(list == null || list.size() == 0){
                wifiError++;
                //binding.networkWifi.setText("WIFI老化结束, 异常, 扫描不到WIFI设备.");
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        repeat();
                    }
                }, 5000);
            }
        }
    };

    private void setSound(int progress){
        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mNowVolume = (int) (mMaxVolume * progress / 100);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mNowVolume, AudioManager.FLAG_PLAY_SOUND);
        binding.value.setText(progress + "%");
    }


    // private TempModuleCallback tempModuleCallback = new TempModuleCallback() {
    // @Override
    //    public void onReadInfo(String info) {
    //        handler.post(new Runnable() {
    //           @Override
    //           public void run() {
    //               binding.tempText.append(info);
    //            }
    //        });
    //    }
//
    //    @Override
    //    public void onCallback(SparseArray<String> tempArray, final Bitmap thermalImaging) {
    // final String temp = tempArray.get(0);
    //  handler.post(new Runnable() {
    //      @Override
    //       public void run() {
    //          binding.tempText.setText(temp);
    //          binding.tempImage.setImageBitmap(thermalImaging);
    //       }
    //   });
    //  }
    //   };


    private MyTimerTask timerTask;
    private long playTime;  //已经播放了多长时间
    private boolean openLampLight;

    private long lastScanTime = 0;
    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            playTime += 1000;
//            long day = playTime / (1000 * 24 * 60 * 60); //单位天
//            long hour = (playTime - day * (1000 * 24 * 60 * 60)) / (1000 * 60 * 60); //单位时
//            long minute = (playTime - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60)) / (1000 * 60); //单位分
//            long second = (playTime - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000;//单位秒

            // if(isFinishing()){
//                gpioLampLight.off();
            //      return;
            //   }
            //   if(openLampLight){
//                gpioLampLight.off();
            //  }else{
//                gpioLampLight.onWhite();
//}
            openLampLight = !openLampLight;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    binding.time.setText("已老化时间: " + timeFormat(playTime));
                }
            });
        }
    }

    public static String timeFormat(long time){
        long day = time / (1000 * 24 * 60 * 60); //单位天
        long hour = (time - day * (1000 * 24 * 60 * 60)) / (1000 * 60 * 60); //单位时
        long minute = (time - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60)) / (1000 * 60); //单位分
        long second = (time - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000;//单位秒
        return String.format("%d天:%d时:%d分%d秒", day, hour, minute, second);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //  tempModule.start(tempModuleCallback);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //  tempModule.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //  tempModule.onDestroy();

        if(binding.videoView.isPlaying()){
            binding.videoView.stopPlayback();
        }

        if(timerTask != null){
            timerTask.cancel();
        }

        handler.removeCallbacksAndMessages(null);
//        gpioLampLight.off();
    }
}